<template>
  <!--  TODO 3->付款单 -->
  <el-dialog v-model="visible" title="付款单" destroy-on-close width="60%" :close-on-click-modal="false" @close="close">
    <div class="mb-2 flex items-center text-sm">
      <el-form :model="formData" :rules="formRules" size="small" ref="paymentOrderFormRef" label-width="110px" class="drawer-form">
        <el-form-item prop="title" label="主题：">
          <el-input v-model="formData.title" placeholder="请输入事项主题" maxlength="32" clearable style="width: 400px;"/>
        </el-form-item>
        <el-form-item label="描述：" prop="content">
          <editor v-model="formData.content" placeholder="请输入事项描述" height="250px"/>
        </el-form-item>
        <el-form-item label="关联：">
          <!--     废弃     <module-relate-by-money :relate-items="formData.relateItems" :selected="selectedCode"/>-->
<!--          关联订单时 添加到下方表格中-->
          <module-relate :relateItems="changeRelateItems" :limiter="limiter" @required="required" @change="changeRelateItems"/>
        </el-form-item>
        <el-form-item prop="paymentTime" :label="currentFormState === 2 ? '付款日期：' : '计划付款日期：'">
          <el-date-picker style="width:125px;" v-model="formData.paymentTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date" placeholder="请选择日期" size="small"/>
        </el-form-item>
<!--        付款类型（钱权限的人添加数据字典，选填）-->
        <el-form-item prop="paymentType" label="付款类型：">
          <el-select v-model="formData.paymentType" style="width: 300px; height: 26px;" size="small" placeholder="请选择" clearable @change="changePaymentType">
            <el-option v-for="item in paymentTypeOption" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item prop="expenditureType" label="支出类别：" v-if="currentFormState === 2">
          <el-select v-model="formData.expenditureType" style="width: 300px; height: 26px;" size="small" placeholder="请选择" clearable>
            <el-option v-for="item in expenditureOption" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="currentFormState === 0 || currentFormState === 1">
          <el-table :data="orderList">
<!--            订单表格 -->
          </el-table>
        </el-form-item>
        <el-form-item label="合计付款金额：" v-if="currentFormState === 0 || currentFormState === 1">
          <span style="font-weight: 700">{{formData.amount}}</span><span style="margin-left: 5px">元</span>
          <span style="margin-left: 50px">大写：{{cnAmount}}</span>
          <el-button size="small" @click="handlePayment" v-if="currentFormState === 0"
                     style="margin-left: 50px" type="primary" icon="ele-Money">付款</el-button>
        </el-form-item>
        <el-form-item prop="amount" label="本次付款金额：" v-if="currentFormState === 2">
          <span style="font-weight: 700">{{formData.amount}}</span><span style="margin-left: 5px">元</span>
        </el-form-item>
        <el-form-item label="收款账号信息：" v-if="currentFormState === 1 || currentFormState === 2 || currentFormState === 3">
          <el-input v-model="formData.accountNumberInfo" placeholder="请输入收款账号信息" size="small" clearable style="width: 350px;"/>
          <el-button size="small" @click="handlePayment" style="margin-left: 50px" type="primary"
                     v-if="currentFormState === 0 || currentFormState === 1" icon="ele-Money">付款</el-button>
        </el-form-item>
        <el-form-item prop="lineFile" label="附件：">
          <el-upload class="upload-demo" drag
                     :action="action"
                     :multiple="false"
                     :auto-upload="false"
                     :headers="headers"
                     @change="changeFile"
                     style="width:100%">
            <el-icon class="el-icon--upload">
              <ele-UploadFilled/>
            </el-icon>
            <div class="el-upload__text">
              拖拽上传或 <em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="已收发票：">
          <el-button size="small" type="primary" icon="ele-CirclePlusFilled" @click="addInvoice">添加发票</el-button>
        </el-form-item>
        <el-form-item prop="remark" label="备注：" class="remark-item">
          <el-input type="textarea" v-model="formData.remark"></el-input>
        </el-form-item>
        <el-form-item prop="confirmedBy" label="付款确认人：">
          <el-select v-model="formData.confirmedBy" style="width: 300px; height: 26px;" size="small" placeholder="请选择" clearable>
            <el-option v-for="item in userOption" :label="item.nickname" :value="item.userId"/>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
          <span class="dialog-footer">
            <el-button size="small" @click="cancel(paymentOrderFormRef)">关闭</el-button>
            <el-button size="small" type="primary" icon="ele-Check" @click="submit(paymentOrderFormRef)">保存</el-button>
          </span>
    </template>
  </el-dialog>
</template>

<script>
import {computed, reactive, ref, toRefs, watch} from "vue";
import Editor from '/@/components/editor/index.vue'
import ModuleRelate from '/@/views/matter/components/ModuleRelate.vue'
import ModuleRelateByMoney from '/@/views/matter/components/ModuleRelateByMoney.vue'
import { Session } from '/@/utils/storage'
import {numToChinese,analysisAssociation} from '/@/utils/common'
import {getEnterpriseUsers} from '/@/api/sys/user';
import {ElMessage} from "element-plus";

export default {
  name: "PaymentOrder",
  emits:['onSubmit','update:dialogDrawer'],
  props: {
    dialogDrawer: {
      type: Boolean,
      default: true,
    },
    type: {
      type: String,
      default: null,
    },
  },
  components: {
    Editor,
    ModuleRelateByMoney,
    ModuleRelate
  },
  setup(props, context) {
    let paymentOrderFormRef = ref()
    let changeRelateItems = ref([])
    const { dialogDrawer,type} = toRefs(props)
    //监听当前表单类型变化
    watch(changeRelateItems , (newVal) => {
      newVal.forEach(item=>{
        const labelName = analysisAssociation(item.label)
        if(labelName === '供应商'){
          //未尽必选

          //API获取字典
          state.paymentTypeOption = []
          // if(是否关联电商单){
          //   state.isAssociationOrder = true
          //   state.currentFormState = 0
          // }else{
          //   //那就是普通订单
          //   state.currentFormState = 1
          // }
        }else if(labelName === '客户'){
          //未尽必选

          //API获取字典
          state.paymentTypeOption = []
          // if(是否关联电商单){
          //   state.isAssociationOrder = true
          //   state.currentFormState = 0
          // }else{
          //   //那就是普通订单
          //   state.currentFormState = 1
          // }
        }else{
          //state.currentFormState = 2 //未关联订单
          state.paymentTypeOption = [
            {
              label:'其他付款',
              value:'0'
            },
            {
              label:'采购付款',
              value:'1'
            },
            {
              label:'销售退款',
              value:'2'
            }
          ]
        }
      })

    },{deep: true})
    let visible = computed({
      get: () => {
        if (dialogDrawer.value){
          // if (是否为执行人打开){
          //   state.currentFormState = 3
          // }

          getEnterpriseUsers().then(res => {
            state.userOption = res.data
          })
          state.cnAmount = numToChinese(state.formData.amount)
        }
        return dialogDrawer.value
      },
      set: val => context.emit('update:dialogDrawer', val)
    })
    const state = reactive({
      //控制付款单显示效果
      currentFormState:3, //0->关联电商单  1->关联非电商单  2->未关联订单  3->执行人打开  默认未关联订单->2
      cnAmount:'',
      isAssociationOrder:false, //默认未关联电商单
      formData:{
        title:'',
        content:'',
        relateItems:[],
        paymentTime:'',
        expenditureType:'', //支出类别
        paymentType:'',
        accountNumberInfo:'111222333444555666',
        amount:0,
        remark:''
      },
      formRules:{
        paymentType:[{ required: true, trigger: 'blur', message: '请选择'}],
      },
      orderList:[],
      required:[],
      action: '#',
      headers: {'17work': Session.get('token')},
      selectedCode: {
        code: 'Money',   // 一级关联项数据code
        dataId: null // 二级关联项数据id
      },
      userOption:[],
      expenditureOption:[
        {
          label:'支出类别',
          value:'0'
        }
      ],
      paymentTypeOption:[
        {
          label:'其他付款',
          value:'0'
        },
        {
          label:'采购付款',
          value:'1'
        },
        {
          label:'销售退款',
          value:'2'
        }
      ],
      matterTypeOption:[  //考虑放到字典
        {
          label:'其他付款',
          value:'0'
        },
        {
          label:'采购付款',
          value:'1'
        },
        {
          label:'销售退款',
          value:'2'
        },
        {
          label:'付款单',
          value:'3'
        },
        {
          label:'报销单',
          value:'4'
        },
        {
          label:'备用金',
          value:'5'
        },
        {
          label:'备用金(还款)',
          value:'6'
        }
      ],
      limiter:{
        module:"paymentOrder", //代表哪一个钱模块
        number:null  //代表限制编号
      },
    })


    /**
     * 通用方法
     */
        //关闭时触发
    const close = () => {
          context.emit('update:dialogDrawer', false)
        }
    //提交
    const submit = (formEl) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (!valid) return // 必填没有填就直接结束
        context.emit('onSubmit', true)
      })
    }
    //取消
    const cancel = (formEl) => {
      if (!formEl) return
      formEl.resetFields()
      context.emit("update:dialogDrawer", false)
    }
    //文件变更时
    const changeFile = (file,fileList) => {
      state.fileList = fileList
    }
    //变更事项类型
    const changeType = (val) => {
      state.limiter.number = val
    }
    //处理付款
    const handlePayment = () => {

    }
    //添加发票
    const addInvoice = () => {

    }
    //修改付款类型
    const changePaymentType = (val) => {
      //只有 在状态2情况下需要限制
      if(state.currentFormState === 2){
        state.limiter.number = val
      }
    }

    return{
      ...toRefs(state),
      dialogDrawer,
      visible,
      type,
      paymentOrderFormRef,
      changeRelateItems,
      Editor,
      ModuleRelateByMoney,
      ModuleRelate,
      close,
      submit,
      cancel,
      changeFile,
      changeType,
      handlePayment,
      addInvoice,
      changePaymentType,

    }

  }
}
</script>

<style scoped>

</style>
